package com.cheung.leetcode.backtrack;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.backtrack
 * @Author :  cheungming
 * @CreateTime : 2024-05-26 09:29:26
 * @Description : 子集
 * @Version : 1.0
 */
public class Code90Test {

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        if (nums.length == 0) {
            return new ArrayList<>();
        }
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        backtrack(nums, 0, new ArrayList<>(), res);
        return res;
    }

    private void backtrack(int[] nums, int start, List<Integer> path, List<List<Integer>> res) {
        res.add(new ArrayList<>(path));
        if (start >= nums.length) {
            return;
        }
        for (int i = start; i < nums.length; i++) {
            // 去重.在当前层不能重复，在不同层之间可以重复，所以这里i>start而不是i>0
            if (i > start && nums[i] == nums[i - 1]) {
                continue;
            }
            path.add(nums[i]);
            backtrack(nums, i + 1, path, res);
            path.remove(path.size() - 1);
        }
    }


    @Test
    public void test1() {
        int[] nums = {1, 2, 2};
        System.out.println(subsetsWithDup(nums));
    }


    @Test
    public void test2() {
        int[] nums = {0};
        System.out.println(subsetsWithDup(nums));
    }
}
